package com.magicode.screen.react.module;

/**
 * Created by wxt on 2016/9/2.
 */
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppContext;
import com.magicode.screen.AppManager;
import com.magicode.screen.api.remote.MgcApi;
import com.magicode.screen.images.JointBitmapView;
import com.magicode.screen.images.UriAsBitmap;
import com.magicode.screen.settingutil.ClearCacheUtil;
import com.magicode.screen.settingutil.UserExitUtil;
import com.magicode.screen.settingutil.UserHeadPicUtil;
import com.magicode.screen.settingutil.VersionUtil;
import com.magicode.screen.share.IntentShareUtil;
import com.magicode.screen.thirdPart.wx.WxPayUtil;
import com.magicode.screen.util.UIHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Mini-zy on 16/7/18.
 */
public class JsAndroidModule extends ReactContextBaseJavaModule{

    private static final String MODULE_NAME="JsAndroid";
    private Boolean status = false;
    private static final int TAKE_PHOTO_REQUEST_CODE = 1;

    public JsAndroidModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }


    @Override
    public String getName() {
        return MODULE_NAME;
    }

    @ReactMethod
    public void jsOpenWXPayActivity(String ruleId){
        UIHelper.showWXPayActivity(getCurrentActivity(),ruleId);
    }
    @ReactMethod
    public void jsOpenAliPayActivity(String ruleId){
        UIHelper.showAliPayActivity(getCurrentActivity(),ruleId);
    }
    @ReactMethod
    public void jsOpenMainTabActivity(){
        UIHelper.showMainTabActivity(getCurrentActivity());
    }

    @ReactMethod
    public void jsOpenThirdPartyLoginActivity(String  type){
        UIHelper.showThirdPartyLoginActivity(getCurrentActivity(),type);
    }

    /**
     * 提交支付接口
     * @param type
     * @param entityId
     * @param amount
     */
    @ReactMethod
    public void confirmPay( String  type , Integer amount , String userToken, String entityId){
        WxPayUtil wpu = new WxPayUtil();
        wpu.setCurrentActivity(getCurrentActivity());
        AsyncHttpResponseHandler prePayHandler = wpu.getPrePayHandler();
//        String userToken =  AppContext.getInstance().getProperty("user.userToken");

        MgcApi.outerpay( userToken,type,amount, prePayHandler, entityId);

    }
    /**
     * 跳转到权限设置界面
     */
    @ReactMethod
    public void getAppDetailSettingIntent(){
        MgcApi.getAppDetailSettingIntent(getCurrentActivity() );
    }
    @ReactMethod
    public void jsGetLoginUserInfo(
            Promise promise) {
        try {

            WritableMap map = Arguments.createMap();
            String usrtId = AppContext.getInstance().getProperty("user.userId");
                map.putString("userId", AppContext.getInstance().getProperty("user.userId"));
                map.putString("userName", AppContext.getInstance().getProperty("user.userName"));
                map.putString("loginName", AppContext.getInstance().getProperty("user.loginName"));
                map.putString("userToken", AppContext.getInstance().getProperty("user.userToken"));
                map.putString("userTokenRefreshTime", AppContext.getInstance().getProperty("user.userTokenRefreshTime"));
                map.putString("picMinPath", AppContext.getInstance().getProperty("user.picMinPath"));
                map.putString("picNormalPath", AppContext.getInstance().getProperty("user.picNormalPath"));
                AppContext.getInstance().cleanLogin();
            promise.resolve(map);
        } catch (IllegalViewOperationException e) {
            promise.reject(e.getMessage());
        }
    }

    @ReactMethod
    public void jsOpenJointBitmap(
            String imagesString,
            Callback errorCallback,
            Callback successCallback){
        try {
            List<Bitmap> list = new ArrayList<Bitmap>();
            UriAsBitmap uriAsBitmap = new UriAsBitmap(getCurrentActivity());

            if(null!=imagesString && imagesString.length()>0){
                String[] listImage=new String[imagesString.length()];
               listImage[0]=imagesString;
                if (null!=listImage) {
                    for (String imagePath : listImage) {
                        Uri imageUri = Uri.fromFile(new File(imagePath));
                        Bitmap bit = uriAsBitmap.decodeUriAsBitmap(imageUri);
                        list.add(bit);
                    }
                }
            }

            JointBitmapView  view = new JointBitmapView(getCurrentActivity(), list);
            successCallback.invoke(view.getImgPath());
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }

    }
    @ReactMethod
    public void jsOpenShareActivity(
        String  imgPath,
        String  type,
        Callback errorCallback,
        Callback successCallback){
            try {
                IntentShareUtil shareUtil=new IntentShareUtil();
                status = shareUtil.handleImageShare(getCurrentActivity(),imgPath,type);
                successCallback.invoke(status);
            } catch (IllegalViewOperationException e) {
                errorCallback.invoke(e.getMessage());
            }
    }
    @ReactMethod
    public void jsClearCache(
        Callback errorCallback,
        Callback successCallback){
            try {
                ClearCacheUtil clearCacheUtil=new ClearCacheUtil(getCurrentActivity());
                String cacheSize= clearCacheUtil.caculateCacheSize();
                status= clearCacheUtil.clearAppCache(getCurrentActivity());//清除缓存
                successCallback.invoke(status, cacheSize);
            } catch (IllegalViewOperationException e) {
                errorCallback.invoke(e.getMessage());
            }

    }

    @ReactMethod
    public void jsOpenUserHeadPicActivity(
 //       UIHelper.showUserHeadPicActivity(getCurrentActivity());
             int tag,
             Callback errorCallback,
             Callback successCallback) {
        try {
                UserHeadPicUtil userHead=new UserHeadPicUtil(getCurrentActivity());
                // 获取上传后的头像路径
                String  userPic = userHead.goToSelectPicture(tag);
                successCallback.invoke(status, userPic);
            } catch (IllegalViewOperationException e) {
                errorCallback.invoke(e.getMessage());
            }
    }
    @ReactMethod
    public void jsVersion(
            Callback errorCallback,
            Callback successCallback){
        try {
            VersionUtil  version=new VersionUtil(getCurrentActivity());
            Map versionMap=version.getNewVersion();
            successCallback.invoke(versionMap.get("isUpdate"),versionMap.get("newVersionCode"));
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
    @ReactMethod
    public void jsVersionqqdownloader(
            Callback errorCallback,
            Callback successCallback){
        try {
            VersionUtil  version=new VersionUtil(getCurrentActivity());
            version.versionqqdownloader();
            successCallback.invoke(true);
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
    @ReactMethod
    public void jsGetVersionName(
            Callback errorCallback,
            Callback successCallback){
        try {
            VersionUtil  versionUtil=new VersionUtil(getCurrentActivity());
            String versionName=versionUtil.getVersionName(getCurrentActivity());
            successCallback.invoke(versionName);
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
    @ReactMethod
    public void jsUserExit(
            Callback errorCallback,
            Callback successCallback){
        try {
            UserExitUtil  userExitUtil=new UserExitUtil(getCurrentActivity());
            status=userExitUtil.appExit();
            successCallback.invoke(status);
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
    @ReactMethod
    public void jsOpenAppExit(){
        // 退出
        AppManager.getAppManager().AppExit(getCurrentActivity());
    }

    /**
     * 从Native 获得Host地址:
     * 格式:   http://app.media-plus.cn/
     */
    @ReactMethod
    public void jsGetHost( final Callback callback) {
        try {
            callback.invoke(UIHelper.getServerUrl(getCurrentActivity()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @ReactMethod
    public void jsGetServerUrl(
            Callback errorCallback,
            Callback successCallback){
        try {
            String  server=UIHelper.getServerUrl(getCurrentActivity());
            successCallback.invoke(server);
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
    /**
     * 此方法是为了解决返回键退出程序后,ToastAndroid不会消失的bug
     */
    @ReactMethod
    public void onBackPressed(String para) {
        Intent setIntent = new Intent(Intent.ACTION_MAIN);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getCurrentActivity().startActivity(setIntent);
        if(para.equals("finish")){
            getCurrentActivity().finish();
        }
        else {
            getCurrentActivity().onBackPressed();
        }
    }
}
